//
//  VideoPlayerModel.swift
//  sss
//
//  Created by 顾佳槟 on 2018/3/6.
//  Copyright © 2018年 lancoo. All rights reserved.
//

import Foundation
import AVFoundation

class VideoPlayerModel : NSObject{
    
    /** *音频列表 */
    var MusicInfoModelList = [MusicInfoModel] ()
    /** *当前播放音频 */
    @objc dynamic var currentPlayMusic:MusicInfoModel?
    /** *当前音频播放进度 */
    @objc dynamic var currentProgress:NSNumber = NSNumber.init(value: 0.0)
    /** *当前音频播放进度 */
    @objc dynamic var isPlaying:NSNumber = NSNumber.init(value: false)
    /** *时间观察 */
    private var timeObserve : Any?
    /** *当前时长 */
    final var currentTime : NSInteger = 0
    /** *总时长 */
    final var totalTime : NSInteger = 0
    /** *播放类型 */
    
    
    var player:AVPlayer?
    
    var playerItem:AVPlayerItem?
    
    override init(){
        super.init()
    }
    
    deinit {
        if self.player != nil {
            self.playerItem?.removeObserver(self, forKeyPath: "status")
            self.playerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
        }
        
        self.player?.pause()
    }
    
    func requestData() {
        
        let paths = Bundle.main.paths(forResourcesOfType: "mp3", inDirectory: nil)
        
        for path in paths {
            let avURLAsset = AVURLAsset(url: URL.init(fileURLWithPath: path))
            let musicModel:MusicInfoModel = MusicInfoModel()
            
            for i in avURLAsset.availableMetadataFormats {
                
                for j in avURLAsset.metadata(forFormat: i) {
                    //歌曲名
                    if j.commonKey!.rawValue == "title"{
                        musicModel.videoTitle = j.value as? String
                        
                    }//封面图片
                    if j.commonKey!.rawValue == "artwork"{
                        musicModel.image=UIImage.init(data: (j.value as? Data)!)// 这里是个坑坑T T
                    }//专辑名
                    if j.commonKey!.rawValue == "albumName"{
                        musicModel.albun=j.value as? String
                    }
                    //歌手
                    if j.commonKey!.rawValue == "artist"{
                        musicModel.artist=j.value as? String
                    }
                }
                
            }
            musicModel.videoPlayPath=URL.init(fileURLWithPath: path)

            MusicInfoModelList.append(musicModel)
        }
        
        self.currentPlayMusic = MusicInfoModelList.first!
        
        resetPlayInfo()
    }
    
    func start() {
        self.player?.play()
        self.isPlaying = NSNumber.init(value: true)
    }
    
    func stop() {
        self.player?.pause()
        self.isPlaying = NSNumber.init(value: false)
    }
    
    func next() {
        
        stop()
        
        self.currentProgress = NSNumber.init(value: 0.0)
        
        let index = self.MusicInfoModelList.index(of: self.currentPlayMusic!)
        
        self.currentPlayMusic = self.MusicInfoModelList[ index! + 1 <= self.MusicInfoModelList.count - 1 ? index! + 1 : 0]
        
        resetPlayInfo()
        
        var s:[Int:String] = [1:"one"]
        
        s.updateValue("one 的新值", forKey: 1)
    }
    
    private func resetPlayInfo(){
        if self.player != nil {
            self.playerItem?.removeObserver(self, forKeyPath: "status")
            self.playerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
        }
        
        self.playerItem = AVPlayerItem.init(url: (self.currentPlayMusic?.videoPlayPath)!)
        self.player = AVPlayer.init(playerItem: self.playerItem!)
        
        //监听
        self.playerItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
        self.playerItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
    }
}

extension VideoPlayerModel{
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let playerItem = object as? AVPlayerItem
        if (keyPath == "status") {
            if (playerItem?.status == AVPlayerItemStatus.readyToPlay) {
                print("AVPlayerStatusReadyToPlay")
                let duration = self.playerItem?.duration// 获取视频总长度
                print("movie total duration:%f",CMTimeGetSeconds(duration!))
                
                addTimeObserve()
                
            } else if (playerItem?.status == AVPlayerItemStatus.failed) {
                print("AVPlayerStatusFailed");
            }
        } else if (keyPath == "loadedTimeRanges") {
            if playerItem?.status != AVPlayerItemStatus.readyToPlay{
                return;
            }

            let timeInterval = availableDuration()// 计算缓冲进度
            print("Time Interval:%f",timeInterval);
            
            let duration = playerItem?.duration
            let totalDuration = CMTimeGetSeconds(duration!);
            
            print("loadTimePrecent:%0.2f%",timeInterval / totalDuration * 100)
        }
    }
    
    private func availableDuration() -> TimeInterval{
        let loadedTimeRanges = self.player?.currentItem?.loadedTimeRanges
        let timeRange = loadedTimeRanges?.first?.timeRangeValue // 获取缓冲区域
        let startSeconds = CMTimeGetSeconds((timeRange?.start)!)
        let durationSeconds = CMTimeGetSeconds((timeRange?.duration)!)
        let result = startSeconds + durationSeconds// 计算缓冲总进度
        return result
    }
    
    /*
     * 实时刷新数据
     */
    private func addTimeObserve(){
        self.timeObserve = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1), queue: nil, using: { [weak self](time) in
//            if #available(iOS 10.0, *) {
//                if self?.player?.timeControlStatus == .playing {
//                    self?.status = PlayerStatus.PlayerPlaying
//                    self?.viewModel?.playOrPauseBtn?.isSelected = false
//                }else if self?.player?.timeControlStatus == .paused {
//                    self?.status = PlayerStatus.PlayerPaused
//                    self?.viewModel?.playOrPauseBtn?.isSelected = true
//                }else if self?.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
//                    self?.status = PlayerStatus.PlayerBuffering
//                    self?.viewModel?.playOrPauseBtn?.isSelected = true
//                }
//            }else{
//                //ios 10.0 以下
//                if self?.player?.currentItem?.status == .readyToPlay {
//                    self?.status = PlayerStatus.PlayerPlaying
//                    self?.viewModel?.playOrPauseBtn?.isSelected = false
//                }else{
//                    self?.status = PlayerStatus.PlayerFaild
//                    self?.viewModel?.playOrPauseBtn?.isSelected = true
//                }
//            }
            if (self?.playerItem != nil) {
                let currentItem = self?.playerItem
                let currentTime = CMTimeGetSeconds((currentItem?.currentTime())!)
                
                let totalTime = CMTimeGetSeconds(CMTimeMake((currentItem?.duration.value)!, (currentItem?.duration.timescale)!))
                
                ///更新进度条,时间
                if (currentItem?.seekableTimeRanges.count)! > 0 && (currentItem?.duration.timescale)! != 0 {
                    self?.totalTime = NSInteger(totalTime)
                    self?.currentTime = NSInteger(currentTime)
                    self?.currentProgress = NSNumber.init(value: Float(currentTime / totalTime))
                }
            }
            
        })
    }
}

class MusicInfoModel:NSObject{
    
    //音频缩略图
    var image:UIImage?
    //音频标题
    var videoTitle:String?
    //音频播放地址
    var videoPlayPath:URL?
    //歌手名字
    var artist:String?
    //音频专辑名称
    var albun:String?
    
}
